import { Toast } from 'vant';

function _clearClassName (quote) {
    // 该方法时清除某些元素的指令的类名
    const arr = Array.from(quote.children);
    arr.filter(value => {
        if (value.className.includes('active')) {
            value.className = value.className.replace(/active/, '');
        }
    });
}

function checkUserLogin (that) {
    // 如果用户未登录访问一些特定的页面之前拦截请求，要去用户登录
    if (!that.$store.state.isLogin) {
        that.$dialog
            .alert({
                title: '提示',
                message: '您还未登录跑腿侠，请先登录再操作',
                confirmButtonText: '登录',
                closeOnClickOverlay: true
            })
            .then(() => {
                // 用户单击了登录按钮
                that.$router.push('/login');
            })
            .catch(() => {
                console.log('用户未单击按钮');
            });
        return false;
    } else {
        return true;
    }
}

/**
 * 检查用户的手机号码是否正确
 * @param phone
 * @returns {boolean}
 */
function checkPhoneRight (phone) {
    const mobile = /^[1][3,4,5,7,8][0-9]{9}$/;
    return mobile.test(phone);
}

/**
 * @return {number}
 */
function ScreenCanUseHeight (tabBarHeight = 0) {
    const NAV_BAR_HEIGHT = 47; // 导航栏高度是固定的
    return document.documentElement.clientHeight - tabBarHeight - NAV_BAR_HEIGHT;
}

function loadingToast (msg) {
    Toast.loading({
        message: msg || '正在处理中...',
        loadingType: 'spinner',
        duration: 0,
        forbidClick: true
    });
}

function successToast (msg, fn = undefined) {
    Toast.clear();
    Toast.success({
        message: msg || '更新成功',
        duration: 1500,
        onClose: fn,
        forbidClick: true
    });
}

function failToast (msg, fn = undefined, duration = 1500) {
    Toast.clear();
    Toast.fail({
        message: msg || '更新失败',
        icon: 'clear',
        duration: duration,
        onClose: fn,
        forbidClick: true
    });
}

function jsonTransformData (jsonData) {
    const formData = new FormData(); // 构造一个formData
    Object.keys(jsonData).forEach(item => {
        if (Array.isArray(jsonData[item])) {
            // 数组的话继续循环，需要判断数组中的每一项是否实包含content
            const urlArray = [];
            jsonData[item].forEach((item, index) => {
                // eslint-disable-next-line no-prototype-builtins
                if (item.hasOwnProperty('content')) {
                    formData.append('image[' + index + ']', item.file);
                } else {
                    urlArray.push(item.url);
                }
            });
            formData.append(item, JSON.stringify(urlArray));
        } else {
            formData.append(item, jsonData[item]);
        }
    });
    return formData;
}

export default {
    jsonTransformData,
    _clearClassName,
    checkUserLogin,
    checkPhoneRight,
    ScreenCanUseHeight,
    loadingToast,
    successToast,
    failToast
};
